<template>
  <view class="body">
    <u-popup v-model="showAd" mode="bottom" safe-area-inset-bottom>
      <view class="picker-view-title">
        <div class="left" @click="showAd = false">取消</div>
        <div class="right" @click="confirm">确定</div>
      </view>
      <picker-view
        indicator-style="height:50rpx;"
        :value="defaultIndex"
        @change="selectChange"
        class="picker-view"
      >
        <picker-view-column>
          <view
            class="item"
            v-for="(item, index) in districtList_1"
            :key="index"
            >{{ item.name }}</view
          >
        </picker-view-column>
        <picker-view-column>
          <view
            class="item"
            v-for="(item, index) in districtList_2"
            :key="index"
            >{{ item.name }}</view
          >
        </picker-view-column>
        <picker-view-column>
          <view
            class="item"
            v-for="(item, index) in districtList_3"
            :key="index"
            >{{ item.name }}</view
          >
        </picker-view-column>
      </picker-view>
    </u-popup>

    <view class="formBox">
      <view class="formItem">
        <text class="title">骑手名称</text>
        <input
          placeholder="请输入骑手名称"
          v-model="form.real_name"
          :disabled="disabled"
        />
      </view>
      <view class="formItem">
        <text class="title">骑手电话</text>
        <input
          type="tel"
          placeholder="请输入骑手电话"
          v-model="form.mobile"
          :disabled="disabled"
          @blur="mobileBlur(form.mobile)"
        />
      </view>
      <view class="formItem">
        <text class="title">身份证号</text>
        <input
          type="idcard"
          placeholder="请输入身份证号"
          v-model="form.real_code"
          :disabled="disabled"
        />
      </view>
      <view class="formItem" @click="openPop('showAd')">
        <text class="title">城市</text>
        <view class="area-info">
          <text :class="areaInfo && !disabled ? 'color-black' : ''">{{
            areaInfo || "请选择所在城市"
          }}</text>
          <u-icon size="24" color="#888888" name="arrow-right"></u-icon>
        </view>
      </view>
      <view class="formItem">
        <text class="title">详细地址</text>
        <input
          type="text"
          placeholder="请输入"
          v-model="form.address"
          :disabled="disabled"
        />
      </view>
      <view class="choosePic" style="border-bottom: 1px solid #f1f1f1">
        <view class="title">
          <text>身份证正面</text>
          <!-- <text>（必填）</text> -->
        </view>
        <view
          class="choose"
          v-if="form.real_just_pic == ''"
          @click="addPic('real_just_pic')"
        >
          <text class="iconfont icon-camera"></text>
          <text>上传</text>
        </view>
        <view class="choose" v-else>
          <image :src="form.real_just_pic"></image>
          <text
            class="close iconfont icon-close"
            @click.stop="form.real_just_pic = ''"
          ></text>
        </view>
      </view>

      <view class="choosePic" style="border-bottom: 1px solid #f1f1f1">
        <view class="title">
          <text>身份证反面</text>
          <!-- <text>（必填）</text> -->
        </view>
        <view
          class="choose"
          v-if="form.real_back_pic == ''"
          @click="addPic('real_back_pic')"
        >
          <text class="iconfont icon-camera"></text>
          <text>上传</text>
        </view>
        <view class="choose" v-else>
          <image :src="form.real_back_pic"></image>
          <text
            class="close iconfont icon-close"
            @click.stop="form.real_back_pic = ''"
          ></text>
        </view>
      </view>

      <view class="foot">
        <button type="warn" class="btn" @click="submit" :disabled="disabled">
          {{ disabled ? "正在审核中..." : "提交" }}
        </button>
      </view>
    </view>
  </view>
</template>

<script>
var district = [];

export default {
  data() {
    return {
      form: {
        real_name: "",
        real_code: "",
        mobile: "",
        real_just_pic: "",
        real_back_pic: "",
        province_id: "",
        district_id: "",
        city_id: "",
        address: ""
      },
      disabled: false,
      position: "",
      defaultIndex: [0, 0, 0],
      districtList_1: [],
      districtList_2: [],
      districtList_3: [],
      showAd: false,
      areaInfo: ""
    };
  },
  async onLoad() {
    this.getDistrict();
    const res = await this.$allrequest.distribution.getApplyRider();
    if (res.code) return;

    let {
      state,
      address,
      area,
      mobile,
      real_back_pic,
      real_code,
      real_just_pic,
      real_name
    } = res.data;
    area = JSON.parse(area);
    let { province_id, district_id, city_id, province, city, district } =
      area[0];

    if (!province) {
      this.areaInfo = "";
    } else {
      this.areaInfo = `${province || ""} ${city || ""} ${district || ""}`;
    }

    this.form = {
      address,
      mobile,
      real_back_pic,
      real_code,
      real_just_pic,
      real_name,
      province_id: parseInt(province_id),
      district_id: parseInt(district_id),
      city_id: parseInt(city_id)
    };

    switch (state) {
      case 2:
        this.$utils.showModal(
          "提示",
          "已通过申请，即将跳转配送员主页。",
          false,
          () => {
            this.$utils.toUrl("/distribution/index/index");
          }
        );
        break;

      case 1:
        this.disabled = true;
        break;

      default:
        break;
    }
  },
  methods: {
    mobileBlur(v) {
      if (v == "") {
        this.$utils.toast("请输入骑手电话");
      } else {
        var re = /^1[3,4,5,6,7,8,9][0-9]{9}$/;
        var result = re.test(v);
        if (!result) {
          this.$utils.toast("手机号码格式不正确！");
          this.form.mobile = "";
        }
      }
    },

    addPic(e) {
      if (this.disabled) return;
      this.$utils.uploadImage(1, (res) => {
        this.form[e] = res;
      });
    },

    async submit() {
      const form = JSON.parse(JSON.stringify(this.form));

      if (form.real_name == "") {
        uni.showToast({
          title: "请输入骑手姓名",
          icon: "none"
        });
        return;
      }
      if (form.real_code == "") {
        uni.showToast({
          title: "请输入身份证号",
          icon: "none"
        });
        return;
      }
      if (form.mobile == "") {
        uni.showToast({
          title: "请输入手机号",
          icon: "none"
        });
        return;
      }

      if (form.province_id === "") {
        uni.showToast({
          title: "请选择地区",
          icon: "none"
        });
        return;
      }
      if (form.real_just_pic == "") {
        uni.showToast({
          title: "请上传身份证正面照",
          icon: "none"
        });
        return;
      }
      if (form.real_back_pic == "") {
        uni.showToast({
          title: "请上传身份证反面照",
          icon: "none"
        });
        return;
      }

      form.area = JSON.stringify([
        {
          province_id: form.province_id,
          district_id: form.district_id,
          city_id: form.city_id
        }
      ]);
      delete form.province_id;
      delete form.district_id;
      delete form.city_id;

      const res = await this.$allrequest.distribution.applyRider(form, true);
      if (res.code == 0) {
        uni.showToast({
          title: "提交成功，请等待审核",
          icon: "none",
          image: "",
          duration: 2000
        });
        setTimeout(() => {
          this.$utils.goBack(1);
        }, 2000);
      } else {
        uni.showToast({
          title: res.msg,
          icon: "none"
        });
      }
    },

    openPop(el) {
      if (this.disabled) return;

      this[el] = true;
    },
    async getDistrict() {
      try {
        var res = await this.$allrequest.user.get_district({});
        district = JSON.parse(JSON.stringify(res.data));

        this.districtList_1 = res.data.map((item) => {
          delete item.cityAll;
          return item;
        });

        this.setAddressList();
      } catch (e) {
        //TODO handle the exception
      }
    },
    setAddressList(list = []) {
      let cityList,
        districtList,
        provinceIndex = 0,
        cityIndex = 0,
        districtIndex = 0;

      if (list && list.length) {
        cityList = district.find((el) => String(list[0]) === el.id).cityAll;
        districtList = cityList.find(
          (el) => String(list[1]) === el.id
        ).districtAll;

        provinceIndex = district.findIndex((el) => String(list[0]) === el.id);
        cityIndex = cityList.findIndex((el) => String(list[1]) === el.id);
        districtIndex = districtList.findIndex(
          (el) => String(list[2]) === el.id
        );
      } else {
        let cityAllItem = JSON.parse(JSON.stringify(district[0].cityAll));
        cityList = cityAllItem;
        districtList = cityList[0].districtAll;
      }

      this.districtList_2 = JSON.parse(JSON.stringify(cityList)).map((el) => {
        delete el.districtAll;
        return el;
      });
      this.districtList_3 = districtList;
      this.defaultIndex = [provinceIndex, cityIndex, districtIndex];
    },

    selectChange(e) {
      let indexs = e.detail.value;
      let yDefaultIndex = JSON.parse(JSON.stringify(this.defaultIndex));
      if (yDefaultIndex[0] != indexs[0]) {
        this.defaultIndex = [indexs[0], 0, 0];
      } else if (yDefaultIndex[1] != indexs[1]) {
        this.defaultIndex = [indexs[0], indexs[1], 0];
      } else {
        this.defaultIndex = indexs;
      }

      this.districtList_2 = district[this.defaultIndex[0]].cityAll;
      this.districtList_3 =
        district[this.defaultIndex[0]].cityAll[
          this.defaultIndex[1]
        ].districtAll;
    },

    confirm() {
      this.showAd = false;

      let val = this.defaultIndex;
      let [i1, i2, i3] = val;

      this.form.province_id = this.districtList_1[i1].id;
      this.form.city_id = this.districtList_2[i2].id;
      this.form.district_id = this.districtList_3[i3].id;
      this.areaInfo = [
        this.districtList_1[i1].name,
        this.districtList_2[i2].name,
        this.districtList_3[i3].name
      ].join("-");
    }
  }
};
</script>

<style lang="scss" scoped>
.body {
  min-height: 100vh;
  background: #f8f8f8;
  .formBox {
    padding-left: 30rpx;
    background-color: #fff;
    .formItem {
      padding: 30rpx 0;
      display: flex;
      align-items: center;
      padding-right: 30rpx;
      justify-content: space-between;
      border-bottom: 1px solid #f1f1f1;
      .ttile {
        font-size: 30rpx;
      }

      input {
        flex: 1;
        overflow: hidden;
        text-align: right;
        color: #8c8c8c;
      }
      .chooseClass {
        display: flex;
        align-items: center;
        font-size: 28rpx;
        color: #8c8c8c;
        .iconfont {
          font-size: 24rpx;
        }
      }
    }
    .choosePic {
      padding: 30rpx 0;
      .title {
        display: flex;
        align-items: center;
        font-size: 30rpx;
        color: #1d1d1d;
        text:nth-child(2) {
          color: #8c8c8c;
        }
      }
      .choose {
        position: relative;
        width: 160rpx;
        height: 160rpx;
        border-radius: 10rpx;
        background-color: #f6f6f6;
        margin-top: 30rpx;
        margin-right: 16rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        font-size: 24rpx;
        color: #8c8c8c;
        .iconfont {
          font-size: 60rpx;
        }
        image {
          width: 100%;
          height: 100%;
          border-radius: 10rpx;
        }
        .close {
          position: absolute;
          width: 32rpx;
          height: 32rpx;
          right: -16rpx;
          top: -16rpx;
          background-color: #f0250e;
          color: #fff;
          font-size: 28rpx;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
    }
    .foot {
      margin-top: 60rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      .btn {
        width: 680rpx;
        height: 88rpx;
        line-height: 88rpx;
        text-align: center;
        font-size: 32rpx;
        font-weight: 500;
        border-radius: 999rpx;
      }
      .tip {
        margin-top: 20rpx;
        font-size: 24rpx;
        color: #8c8c8c;
      }
    }
  }
}

.area-info {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  text {
    font-size: 28rpx;
    font-family: PingFang SC;
    font-weight: 400;
    color: #8c8c8c;
  }
  .color-black {
    color: rgb(38, 38, 38);

    input {
      color: rgb(38, 38, 38);
    }
  }
}

.picker-view-title {
  padding: 20rpx;
  font-size: 28rpx;
  color: #1aa034;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .left {
    color: #999;
  }
}

.picker-view {
  width: 750rpx;
  height: 500rpx;

  .item {
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
  }
}
</style>
